//
//  BookRecoder.m
//  ReadJapanese
//
//  Created by 병철 김 on 11. 8. 11..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "BookRecoder.h"


@implementation BookRecoder

- (id)init {
	self = [super init];
	if (self) {
		NSError *error;
		AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setDelegate:self];
		[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
        
        UInt32 doChangeDefaultRoute = 1;
        AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
        
		[session setActive:YES error:&error];
	}
	return self;
}

- (void) recordBook:(NSNumber*) bookId sentence:(NSNumber*) sentenceId {
	if (recorder != nil) {
		[self stopRecord];
	}
	
	NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init];
	[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
	[recordSetting setValue:[NSNumber numberWithFloat:12000.0] forKey:AVSampleRateKey];
	[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
	
	NSError *error;
	NSString *fileName = [NSString stringWithFormat:@"v_%d_%d.caf", [bookId intValue], [sentenceId intValue]];
	NSString *fullFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:fileName];
	NSURL *fileUrl = [NSURL fileURLWithPath:fullFilePath];
	
	recorder = [[AVAudioRecorder alloc] initWithURL:fileUrl settings:recordSetting error:&error];
	[recordSetting release];
	
	[recorder prepareToRecord];
	[recorder recordForDuration:(NSTimeInterval) 60];
}

- (void) stopRecord {
	[recorder stop];
	[recorder release];
	recorder = nil;
}

- (void) playRecordBook:(NSNumber*)bookId sentence:(NSNumber*) sentenceId {
	if (recorder != nil) {
		[self stopRecord];
	}
	if (audioPlayer != nil) {
		[audioPlayer release];
		audioPlayer = nil;
	}
	
	NSString *fileName = [NSString stringWithFormat:@"v_%d_%d.caf", [bookId intValue], [sentenceId intValue]];
	NSString *fullFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:fileName];
	NSURL *fileUrl = [NSURL fileURLWithPath:fullFilePath];
	
	NSError *error;
	audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
	audioPlayer.numberOfLoops = 0;
	[audioPlayer setVolume:1.0];
	[audioPlayer play];
}

- (void)dealloc {
	[recorder release];
	[super dealloc];
}

@end
